<template>
  <div class="containerBox">
    <div id="container"></div>
    <div class="toolbar">
      <a title="download" @click="download">下载</a>
      <a ref="saveDiagram" href="javascript:" title="download BPMN diagram">BPMN</a>
      <a ref="saveSvg" href="javascript:" title="download as SVG image">SVG</a>
    </div>
  </div>
</template>

<script>
import BpmnModeler from 'bpmn-js/lib/Modeler';
import customModule from './customPalette';
import download from 'downloadjs';
import stationInLetter from './stationInLetter';
import voiceRobot from './voiceRobot';
import BpmData from "./BpmData";
export default {
  name: 'App',
  data() {
    return {
      containerEl: null,
      bpmnModeler: null,
      bpmData: new BpmData(),
      element: null,
    };
  },
  mounted() {
    this.containerEl = document.getElementById('container');
    this.bpmnModeler = new BpmnModeler({
      container: this.containerEl,
      additionalModules: [ stationInLetter, voiceRobot]
    });
    // this.create();
    // 新增流程定义
    this.createNewDiagram();

    const self = this;
    this.bpmnModeler.on('selection.changed', e => {
      console.log('selection.changed', e);
      self.element = e.newSelection[0];
    });
    this.bpmnModeler.on('drag.cleanup', e => {
      console.log('drag.cleanup', e);
      // self.element = e.newSelection[0];
    });

    // 好像调用不到哎
    this.bpmnModeler.on('element.changed', e => {
      console.log('element.changed', e)
      if (!self.element) {
        return;
      }
      const { element } = e;

      const { currentElement } = self.element;
      if (!currentElement) {
        return;
      }

      // update panel, if currently selected element changed
      if (element.id === currentElement.id) {
        self.element = element;
      }
      console.log('self.element', self.element);
    });
  },
  methods: {
    // create() {
    //   this.bpmnModeler.createDiagram(() => {
    //     this.bpmnModeler.get('canvas').zoom('fit-viewport');
    //   });
    // },
    createNewDiagram() {
      const bpmnXmlStr = `
      <?xml version="1.0" encoding="UTF-8"?>
        <bpmn2:definitions xmlns:bpmn2="http://www.omg.org/spec/BPMN/20100524/MODEL" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:bpmndi="http://www.omg.org/spec/BPMN/20100524/DI" xmlns:dc="http://www.omg.org/spec/DD/20100524/DC" xmlns:di="http://www.omg.org/spec/DD/20100524/DI" id="sample-diagram" targetNamespace="http://bpmn.io/schema/bpmn" xsi:schemaLocation="http://www.omg.org/spec/BPMN/20100524/MODEL BPMN20.xsd">
          <bpmn2:process id="process1567044459787" name="流程1567044459787">
            <bpmn2:documentation>描述</bpmn2:documentation>
            <bpmn2:startEvent id="StartEvent_01ydzqe" name="开始">
              <bpmn2:outgoing>SequenceFlow_1qw929z</bpmn2:outgoing>
            </bpmn2:startEvent>
            <bpmn2:endEvent id="EndEvent_0pnmjd3" name="结束">
              <bpmn2:incoming>SequenceFlow_0h8za82</bpmn2:incoming>
            </bpmn2:endEvent>
          </bpmn2:process>
          <bpmndi:BPMNDiagram id="BPMNDiagram_1">
            <bpmndi:BPMNPlane id="BPMNPlane_1" bpmnElement="process1567044459787">
              <bpmndi:BPMNShape id="StartEvent_01ydzqe_di" bpmnElement="StartEvent_01ydzqe">
                <dc:Bounds x="532" y="72" width="36" height="36" />
                <bpmndi:BPMNLabel>
                  <dc:Bounds x="539" y="53" width="22" height="14" />
                </bpmndi:BPMNLabel>
              </bpmndi:BPMNShape>
              <bpmndi:BPMNShape id="EndEvent_0pnmjd3_di" bpmnElement="EndEvent_0pnmjd3">
                <dc:Bounds x="532" y="602" width="36" height="36" />
              </bpmndi:BPMNShape>
            </bpmndi:BPMNPlane>
          </bpmndi:BPMNDiagram>
        </bpmn2:definitions>
      `;

      this.bpmnModeler.importXML(bpmnXmlStr, err => {
        // if (err) {
        //   console.error('err', err);
        // } else {
        //   console.log("进来没");
        console.log('err', err);
        this.adjustPalette();
        // }
      });
    },
    // 调整左侧工具栏排版
    adjustPalette() {
      try {
        // 获取 bpmn 设计器实例
        const canvas = document.getElementById('container');
        console.log('canvas', canvas);
        // 左侧的标签组的父标签
        const djsPalette = canvas.children[0].children[1].children[4];
        const djsPalStyle = {
          width: "130px",
          padding: "5px",
          background: "#eee",
          left: "20px",
          borderRadius: 0
        };
        // console.log('djsPalette', djsPalette);
        // 给父标签设置样式
        for (let key in djsPalStyle) {
          djsPalette.style[key] = djsPalStyle[key];
        }
        // 为获取8个不知道啥标签的父标签，以后匹配用
        let palette = djsPalette.children[0];

        console.log('palette', palette);
        // 8个标签组，用来挑选
        let allGroups = palette.children;
        // 设置为none是因为匹配到的这几组件个不想使用，也就不用显示了
        allGroups[0].style["display"] = "none";
        // allGroups[8] = allGroups[3];
        // console.log('allGroups', allGroups);
        // 修改控件样式
        for (let gKey in allGroups) {
          const group = allGroups[gKey];
          // console.log('group', group);
          for (let cKey in group.children) {
            const control = group.children[cKey];
            // console.log('control', control);
            const controlStyle = {
              display: "flex",
              justifyContent: "flex-start",
              alignItems: "center",
              marginBottom: '10px',
              width: "100%",
              padding: "5px"
            };
            if (
                control.className &&
                control.dataset &&
                control.className.indexOf("entry") !== -1
            ) {
              const controlProps = this.bpmData.getControl(
                  control.dataset.action
              );
              // console.log('controlProps', controlProps);
              control.innerHTML = `<div style='font-size: 14px;font-weight:500;margin-left:15px;'>${
                  controlProps["title"]
              }</div>`;
              for (let csKey in controlStyle) {
                control.style[csKey] = controlStyle[csKey];
              }
            }
          }
        }
      } catch (e) {
        console.log(e);
      }

    },
    downloadUtil(content, fileName, mimeType){
      download(
          'data:' + mimeType + ';charset=UTF-8,' + encodeURIComponent(content),
          fileName,
          mimeType
      );
    },
    download() {
      this.bpmnModeler.saveXML({format: true}, (err, xml) => {
        if (xml) {
          this.downloadUtil(xml, 'diagram1.bpmn', 'application/xml');
        }
      });
    },
  }
}
</script>

<style scoped lang="scss">
.containerBox {
  height: calc(100vh - 220px);
  position: relative;
  #container {
    height: calc(100% - 50px);
    //background-color: pink;
    ::v-deep .bjs-powered-by {
      display: none;
    }
  }
  .toolbar {
    position: absolute;
    top: 20px;
    right: 350px;
    a {
      text-decoration: none;
      margin: 5px;
      color: #409eff;
    }
  }
}
</style>
